/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Room;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.Isle;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class RoomJpaController implements Serializable {

    public RoomJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public RoomJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Room room) throws IllegalOrphanException, PreexistingEntityException, Exception {
        if (room.getIsleCollection() == null) {
            room.setIsleCollection(new ArrayList<Isle>());
        }
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = room.getComponent();
        if (componentOrphanCheck != null) {
            Room oldRoomOfComponent = componentOrphanCheck.getRoom();
            if (oldRoomOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type Room whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Component component = room.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                room.setComponent(component);
            }
            Collection<Isle> attachedIsleCollection = new ArrayList<Isle>();
            for (Isle isleCollectionIsleToAttach : room.getIsleCollection()) {
                isleCollectionIsleToAttach = em.getReference(isleCollectionIsleToAttach.getClass(), isleCollectionIsleToAttach.getId());
                attachedIsleCollection.add(isleCollectionIsleToAttach);
            }
            room.setIsleCollection(attachedIsleCollection);
            em.persist(room);
            if (component != null) {
                component.setRoom(room);
                component = em.merge(component);
            }
            for (Isle isleCollectionIsle : room.getIsleCollection()) {
                Room oldIDRoomOfIsleCollectionIsle = isleCollectionIsle.getIDRoom();
                isleCollectionIsle.setIDRoom(room);
                isleCollectionIsle = em.merge(isleCollectionIsle);
                if (oldIDRoomOfIsleCollectionIsle != null) {
                    oldIDRoomOfIsleCollectionIsle.getIsleCollection().remove(isleCollectionIsle);
                    oldIDRoomOfIsleCollectionIsle = em.merge(oldIDRoomOfIsleCollectionIsle);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findRoom(room.getId()) != null) {
                throw new PreexistingEntityException("Room " + room + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Room room) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Room persistentRoom = em.find(Room.class, room.getId());
            Component componentOld = persistentRoom.getComponent();
            Component componentNew = room.getComponent();
            Collection<Isle> isleCollectionOld = persistentRoom.getIsleCollection();
            Collection<Isle> isleCollectionNew = room.getIsleCollection();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                Room oldRoomOfComponent = componentNew.getRoom();
                if (oldRoomOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type Room whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                room.setComponent(componentNew);
            }
            Collection<Isle> attachedIsleCollectionNew = new ArrayList<Isle>();
            for (Isle isleCollectionNewIsleToAttach : isleCollectionNew) {
                isleCollectionNewIsleToAttach = em.getReference(isleCollectionNewIsleToAttach.getClass(), isleCollectionNewIsleToAttach.getId());
                attachedIsleCollectionNew.add(isleCollectionNewIsleToAttach);
            }
            isleCollectionNew = attachedIsleCollectionNew;
            room.setIsleCollection(isleCollectionNew);
            room = em.merge(room);
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setRoom(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setRoom(room);
                componentNew = em.merge(componentNew);
            }
            for (Isle isleCollectionOldIsle : isleCollectionOld) {
                if (!isleCollectionNew.contains(isleCollectionOldIsle)) {
                    isleCollectionOldIsle.setIDRoom(null);
                    isleCollectionOldIsle = em.merge(isleCollectionOldIsle);
                }
            }
            for (Isle isleCollectionNewIsle : isleCollectionNew) {
                if (!isleCollectionOld.contains(isleCollectionNewIsle)) {
                    Room oldIDRoomOfIsleCollectionNewIsle = isleCollectionNewIsle.getIDRoom();
                    isleCollectionNewIsle.setIDRoom(room);
                    isleCollectionNewIsle = em.merge(isleCollectionNewIsle);
                    if (oldIDRoomOfIsleCollectionNewIsle != null && !oldIDRoomOfIsleCollectionNewIsle.equals(room)) {
                        oldIDRoomOfIsleCollectionNewIsle.getIsleCollection().remove(isleCollectionNewIsle);
                        oldIDRoomOfIsleCollectionNewIsle = em.merge(oldIDRoomOfIsleCollectionNewIsle);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = room.getId();
                if (findRoom(id) == null) {
                    throw new NonexistentEntityException("The room with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Room room;
            try {
                room = em.getReference(Room.class, id);
                room.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The room with id " + id + " no longer exists.", enfe);
            }
            Component component = room.getComponent();
            if (component != null) {
                component.setRoom(null);
                component = em.merge(component);
            }
            Collection<Isle> isleCollection = room.getIsleCollection();
            for (Isle isleCollectionIsle : isleCollection) {
                isleCollectionIsle.setIDRoom(null);
                isleCollectionIsle = em.merge(isleCollectionIsle);
            }
            em.remove(room);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Room> findRoomEntities() {
        return findRoomEntities(true, -1, -1);
    }

    public List<Room> findRoomEntities(int maxResults, int firstResult) {
        return findRoomEntities(false, maxResults, firstResult);
    }

    private List<Room> findRoomEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Room.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Room findRoom(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Room.class, id);
        } finally {
            em.close();
        }
    }

    public int getRoomCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Room> rt = cq.from(Room.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
